<?php
if (!isset($website) ) { header('HTTP/1.1 404 Not Found'); die; }

if ( isset($_GET["logout"]) AND is_logged() ) {
  os_logout();
  if ( isset($_SESSION["logout"]) ) {
  header("location: ".$_SESSION["logout"].""); die;
  } else {
  header("location: ".$website.""); die;
  }
}

//Activation - login&code=$code&e=$email
if ( !is_logged() AND isset($_GET["login"]) AND isset($_GET["code"]) AND isset($_GET["e"]) AND strlen($_GET["code"])>=8 ) {
   $code = safeEscape( $_GET["code"]);
   $e = $_GET["e"];
   $errors = "";
   
   if (!preg_match("/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i", $e)) 
   $errors.="<div>".$lang["error_email"]."</div>";
   if ( empty($errors) ) {
   $result = $db->query("SELECT * FROM users WHERE user_email ='".$e."' AND code = '".$code."'");
   
   if ( $db->num_rows($result)>=1 ) {
     $update = $db->query("UPDATE users SET code = '' WHERE user_email ='".$e."' AND code = '".$code."' LIMIT 1");
	 $errors.="<div>Account successfully activated. Now you can login.</div>"; //Not error...just a message
   } else $errors.="<div>Link is not valid or expired</div>";
   
   }
}


//LOGIN
if ( isset( $_GET["login"]) AND !is_logged() AND isset($_POST["login_"] ) ) {
   $email = safeEscape( $_POST["login_email"]);
   $password = safeEscape( $_POST["login_pw"]);
   $errors = "";
   if (!preg_match("/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i", $email)) 
   $errors.="<div>".$lang["error_email"]."</div>";
   if ( strlen($password)<=2 ) $errors.="<div>".$lang["error_short_pw"]."</div>";
   
   if ( empty($errors) ) {
      $result = $db->query("SELECT * FROM users WHERE user_email = '".$email."' LIMIT 1");
	  if ( $db->num_rows($result)>=1 ) {
	  
	  $row = $db->fetch_array($result,'assoc');
	  $CheckPW = generate_password($password, $row["password_hash"]);
	  
	  if (!empty($row["code"]) ) $errors.="<div>".$lang["error_inactive_acc"]."</div>";
	  
	  if ( $CheckPW == $row["user_password"] AND empty($errors)) {
	  $_SESSION["user_id"] = $row["user_id"];
	  $_SESSION["username"] = $row["user_name"];
	  $_SESSION["email"]    = $row["user_email"];
	  $_SESSION["level"]    = $row["user_level"];
	  $_SESSION["can_comment"]    = $row["can_comment"];
	  $_SESSION["logged"]    = time();
	  header("location: ".$website."");
	  }
	  
	 }  else $errors.="<div>".$lang["error_invalid_login"]."</div>";
   }
}

//REGISTER
if ( isset( $_GET["login"]) AND !is_logged() AND isset($_POST["register_"] ) ) {
   $username = safeEscape( trim($_POST["reg_un"]));
   $email = safeEscape( trim($_POST["reg_email"]));
   $password = safeEscape( $_POST["reg_pw"]);
   $password2 = safeEscape( $_POST["reg_pw2"]);
   $registration_errors = "";
   if (!preg_match("/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i", $email)) 
   $registration_errors.="<div>E-mail address is not valid</div>";
   if ( strlen($username)<=2 )  $registration_errors.="<div>".$lang["error_short_un"]."</div>";
   if ( strlen($password)<=2 )  $registration_errors.="<div>".$lang["error_short_pw"]."</div>";
   if ( $password!=$password2 ) $registration_errors.="<div>".$lang["error_passwords"]."</div>";
   
   if ( empty($registration_errors) ) {
     $result = $db->query("SELECT COUNT(*) FROM users WHERE LOWER(user_name) = LOWER('".$username."') ");
	 $r = $db->fetch_row($result);
     if ( $r[0] >=1 )
	 $registration_errors.="<div>".$lang["error_un_taken"]."</div>";
	 
     $result = $db->query("SELECT COUNT(*) FROM users WHERE LOWER(user_email) = LOWER('".$email."') ");
	 $r = $db->fetch_row($result);
     if ( $r[0] >=1 )
	 $registration_errors.="<div>".$lang["error_email_taken"]."</div>";
	 
	  if ( empty($registration_errors) ) {
	  
	  $hash = generate_hash(16,1);
	  $password_db = generate_password($password, $hash);
	  
	  if ($UserActivation == 1) $code = generate_hash(16,1); else $code = '';
	  
	  $result = $db->query("INSERT INTO users(user_name, user_password, password_hash, user_email, user_joined, user_level, user_ip, can_comment, code) VALUES('".$username."', '".$password_db."', '".$hash."', '".$email."', '".(int) time()."', '0', '".EscapeStr($_SERVER["REMOTE_ADDR"])."', '1', '".$code."' ) ");
	  
	  //SEND EMAIL
	  if ($UserActivation == 1) {
	  	    $message = $lang["email_activation1"]." $username,<br />";
	        $message.= $lang["email_activation2"]." $website <br />";
			$message.= $lang["email_activation3"]."<br />";
			$message.= $website."?login&code=$code&e=$email<br />";
	        $message.="------------------------------------------<br />";
	        $message.="$website<br />";
	 
		    //$send_mail = mail($email, "Account Activation", $message, $headers);
			require("inc/class.phpmailer.php");
	        $mail  = new PHPMailer();
			$mail->CharSet = $lang["email_charset"];
			$mail->SetFrom($lang["email_from"], $lang["email_from_full"]);
			$mail->AddReplyTo($lang["email_from"], $lang["email_from_full"]);
			$mail->AddAddress($email, "");
			$mail->Subject = $lang["email_subject_activation"];
			$mail->MsgHTML($message);
			$mail->Send();
	       }
	  
	  }
   }
}


//DELETE COMMENT - ADMIN
if (is_logged() AND isset($_SESSION["level"] ) AND $_SESSION["level"]>=9 AND isset($_GET["delete_comment"]) AND isset($_GET["post_id"]) ) { 
   $id = safeEscape( (int) $_GET["delete_comment"] );
   $pid = safeEscape( (int) $_GET["post_id"] );
   
   $del = $db->query("DELETE FROM comments WHERE id = '".$id."' AND post_id = '".$pid."' LIMIT 1");
   $get = $db->query("SELECT COUNT(*) FROM comments WHERE post_id= '".$pid."' LIMIT 1");
   $r = $db->fetch_row($get);
   $TotalComments = $r[0];
   $update = $db->query("UPDATE news SET comments = '".$TotalComments."' WHERE news_id = '".$pid."' ");
   
   header('location: '.$website.'?post_id='.$pid.'#comments'); die;
}

  if ( isset($_POST["add_comment"]) AND is_logged() AND isset($_GET["post_id"]) AND is_numeric($_GET["post_id"]) AND isset($_SESSION["code"]) AND isset($_POST["code"]) AND isset($_POST["pid"]) ) {
  $id = safeEscape( (int) $_GET["post_id"]);
  $text = my_nl2br( trim($_POST["post_comment"]) );
  //$text = str_replace("\n", "<br />", $text);
  $text = nl2br($text);
  $text = EscapeStr( ($text) );
  $text = (($text));
  $errors = "";
  
  //Check if comments is allowed for this post
  $check = $db->query("SELECT * FROM news WHERE news_id = '".$id."' AND allow_comments = 1");
  if ( $db->num_rows($check)<=0 ) $errors.="<div>".$lang["error_comment_not_allowed"]."</div>";
  
  if ( $_SESSION["code"] != $_POST["code"])  $errors.="<div>".$lang["error_invalid_form"]."</div>";
  if ( $_POST["pid"] != $id )                $errors.="<div>".$lang["error_invalid_form"]."</div>";
  if ( strlen($text)<=3 )   $errors.="<div>".$lang["error_text_char"] ."</div>";
  
  
  if ( empty($errors) ) {
     $result = $db->query("INSERT INTO comments(user_id, page, post_id, text, date, user_ip) 
	 VALUES('".$_SESSION["user_id"]."', 'news', '".(int) $id."', '".$text."', '".time()."', '".$_SERVER["REMOTE_ADDR"]."')");
	 
	 $get = $db->query("SELECT COUNT(*) FROM comments WHERE post_id= '".$id."' LIMIT 1");
	 $r = $db->fetch_row($get);
     $TotalComments = $r[0];
	 $update = $db->query("UPDATE news SET comments = '".$TotalComments."' WHERE news_id = '".$id."' ");
	 
	 if ( $result ) {
	    header("location: ".$website."?post_id=".$id."#comments"); die;
	 }
  }
  
  }

  //GAMES
  if ( isset($_GET["games"]) OR isset($_GET["u"]) ) {
  
  	$HomeTitle = ($lang["game_archive"]);
	$HomeDesc = strip_quotes($lang["game_archive"]);
	$HomeKeywords = strtolower( strip_quotes($lang["game_archive"])).','.$HomeKeywords;
	
	//Get date of first game
	$result = $db->query("SELECT * FROM games WHERE id>=1 AND LOWER(map) LIKE ('%dota%') ORDER BY datetime ASC LIMIT 1");
	
	if ( $db->num_rows($result)>=1 ) {
	  $row = $db->fetch_array($result,'assoc');
	  $StartYear = date("Y", strtotime($row["datetime"]));
	  $StartMonth = date("m", strtotime($row["datetime"]));
	} else  {
	$StartYear = date("Y", time() );
	$StartMonth = date("m", time() );
	}
  
	  
  if ( (isset($_GET["uid"]) AND is_numeric($_GET["uid"])) OR isset($_GET["u"])  ) {
     
	 $sqlFilter = "";
	 
	 if ( isset($_GET["u"]) ) $id = safeEscape( (int) $_GET["u"] );
	 else
	 $id = safeEscape( (int) $_GET["uid"] );
	 
	 if ( isset($_GET["h"]) ) {
	   $hero = safeEscape(strtoupper($_GET["h"]) );
	   $sqlFilter = "AND dp.hero = '".$hero."'";
	   
     $sql = "SELECT s.*, g.id, g.map, g.gamename, g.datetime, g.ownername, g.duration,  g.creatorname, dg.winner, 
	 CASE WHEN(g.gamestate = '17') THEN 'PRIV' ELSE 'PUB' end AS type, s.player, dp.kills, dp.deaths, dp.creepkills, dp.creepdenies, dp.assists, dp.hero, dp.neutralkills, dp.newcolour
	 FROM stats as s 
	 LEFT JOIN gameplayers as gp ON LOWER(gp.name) = LOWER(s.player)
	 LEFT JOIN games as g ON g.id = gp.gameid
	 LEFT JOIN dotagames as dg ON g.id = dg.gameid 
	 LEFT JOIN dotaplayers as dp ON dp.gameid = dg.gameid AND gp.colour = dp.colour
	 WHERE s.id = '".$id."' AND LOWER(g.map) LIKE ('%dota%') AND g.duration>='".$MinDuration."' ".$sqlFilter."
	 ";
	 $result = $db->query($sql);
	 
	$numrows = $db->num_rows($result);
    $result_per_page = $GamesPerPage;
	 } else {
	 
	 $sql = "SELECT COUNT(*) 
	 FROM stats as s 
	 LEFT JOIN gameplayers as gp ON LOWER(gp.name) = LOWER(s.player)
	 LEFT JOIN games as g ON g.id = gp.gameid
	 LEFT JOIN dotagames as dg ON g.id = dg.gameid 
	 WHERE s.id = '".$id."' 
	 AND LOWER(g.map) LIKE ('%dota%') 
	 AND g.duration>='".$MinDuration."' 
	 LIMIT 1";
	 

  $result = $db->query($sql);
  
  $r = $db->fetch_row($result);
  $numrows = $r[0];
  $result_per_page = $GamesPerPage;
  }
  $draw_pagination = 0;
  include('inc/pagination.php');
  $draw_pagination = 1;
	 
	$sql = getUserGames ($id, $MinDuration, $offset, $rowsperpage, $sqlFilter );
	 
  }
  else   
  {
  //FILTER
  $filter  = "";
  
  if ( isset($_GET["m"]) AND is_numeric($_GET["m"]) AND $_GET["m"]<=12 AND $_GET["m"]>=1 ) {
  $m = safeEscape( (int) $_GET["m"] );
  $filter.= "AND MONTH(datetime) = '".$m."'";
  }
  
  if ( isset($_GET["y"]) AND is_numeric($_GET["y"]) AND $_GET["y"]<=date("Y") AND $_GET["y"]>=1998 ) {
  $y = safeEscape( (int) $_GET["y"] );
  $filter.= "AND YEAR(datetime) = '".$y."'";
  }
  
  $result = $db->query("SELECT COUNT(*) FROM games 
  WHERE LOWER(map) LIKE ('%dota%') AND duration>='".$MinDuration."' $filter LIMIT 1");
  
  $r = $db->fetch_row($result);
  $numrows = $r[0];
  $result_per_page = $GamesPerPage;
  $draw_pagination = 0;
  include('inc/pagination.php');
  $draw_pagination = 1;
	  
   $sql = getAllGames($MinDuration, $offset, $rowsperpage, $filter, "datetime DESC" );
	  
    }
  $result = $db->query( $sql  );
		  
	$c=0;
    $GamesData = array();
	
	while ($row = $db->fetch_array($result,'assoc')) {
	$GamesData[$c]["id"]        = (int)($row["id"]);
	$GetMap = convEnt2(substr($row["map"], strripos($row["map"], '\\')+1));
	$Map = explode(".w", $GetMap );
	$GamesData[$c]["map"]  = $Map[0];
	//$GamesData[$c]["map"]  = convEnt2(substr($row["map"], strripos($row["map"], '\\')+1));
	//$GamesData[$c]["map"] = reset( explode(".w", $GamesData[$c]["map"] ) );
	//$GamesData[$c]["map"] = substr($GamesData[$c]["map"],0,20);
	$GamesData[$c]["datetime"]  = ($row["datetime"]);
	$GamesData[$c]["gamename"]  = ($row["gamename"]);
	$GamesData[$c]["ownername"]  = ($row["ownername"]);
	$GamesData[$c]["duration"]  = ($row["duration"]);
	$GamesData[$c]["creatorname"]  = ($row["creatorname"]);
	$GamesData[$c]["winner"]  = ($row["winner"]);
	$GamesData[$c]["type"]  = ($row["type"]);
	
	if ( isset($row["newcolour"]) ) {
	$GamesData[$c]["newcolour"]  = ($row["newcolour"]);
	
	if ( $row["newcolour"] <=5  AND $row["winner"] == 1 )  $GamesData[$c]["win"]  = 1; else 
	if ( $row["newcolour"] >5   AND $row["winner"] == 1 )  $GamesData[$c]["win"]  = 2; else 
	if ( $row["newcolour"] >5   AND $row["winner"] == 2 )  $GamesData[$c]["win"]  = 1; else 
	if ( $row["newcolour"] <=5  AND $row["winner"] == 2 )  $GamesData[$c]["win"]  = 2; 
	} else $GamesData[$c]["newcolour"]  = 0;
	if ( $row["winner"] == 0 ) $GamesData[$c]["win"] = 0;

	
	//REPLAY
	 $duration = secondsToTime($row["duration"]);
     $replayDate =  strtotime($row["datetime"]);  //3*3600 = +3 HOURS,   +0 minutes.
     $replayDate = date("Y-m-d H:i",$replayDate);
     $gametimenew = substr(str_ireplace(":","-",date("Y-m-d H:i",strtotime($replayDate))),0,16);
	 $gid =  (int)($row["id"]);
	 $gamename = $GamesData[$c]["gamename"];
	 include('inc/get_replay.php');
	 
	 if ( file_exists($replayloc) ) $GamesData[$c]["replay"] = $replayloc; else $GamesData[$c]["replay"] = "";
	 //END REPLAY
	
	if (isset($row["hero"]) )         
	{
	$GamesData[$c]["hero"]  = strtoupper($row["hero"]);   
    if ( empty($row["hero"])  ) $GamesData[$c]["hero"] = "blank";
	
	if ( !file_exists("img/heroes/".$GamesData[$c]["hero"].".gif") ) $GamesData[$c]["hero"]  = "blank";
	
	}
	else $GamesData[$c]["hero"]  = "blank";
	if (isset($row["kills"]) )        $GamesData[$c]["kills"]  = ($row["kills"]);   else $GamesData[$c]["kills"]  = "0";
	if (isset($row["deaths"]) )       $GamesData[$c]["deaths"]  = ($row["deaths"]); else $GamesData[$c]["deaths"]  = "0";
	if (isset($row["creepkills"]) )   $GamesData[$c]["creepkills"]  = ($row["creepkills"]);   else $GamesData[$c]["creepkills"]  = "0";
	if (isset($row["creepdenies"]) )  $GamesData[$c]["creepdenies"]  = ($row["creepdenies"]); else $GamesData[$c]["creepdenies"]  = "0";
	if (isset($row["assists"]) )      $GamesData[$c]["assists"]  = ($row["assists"]);       else $GamesData[$c]["assists"]  = "0";
	if (isset($row["neutralkills"]) ) $GamesData[$c]["neutrals"]  = ($row["neutralkills"]); else $GamesData[$c]["neutrals"]  = "0";
	
	if (isset($row["player"]) ) $GamesData[$c]["player"]  = ($row["player"]);
	$c++;
	}
	$db->free($result);	
  }
  
  // ----- > END GAMES
  
  //SINGLE GAME
  if ( isset($_GET["game"]) AND is_numeric($_GET["game"]) ) {
     $gameid = safeEscape( (int) $_GET["game"]);
	 $c=0;
     $GameData = array();
	 
	 $result = $db->query(  getSingleGame( (int)$gameid ) );
	 
	 if ( $db->num_rows($result)<=0 ) { header('location: '.$website.'?404'); die; }
	 
	 $update_view = $db->query("UPDATE games SET views = views + 1 WHERE id = '".(int)$gameid ."' ");
	 
	 $row = $db->fetch_array($result,'assoc');
	 
	 $GameData[$c]["creatorname"]  = ($row["creatorname"]);
	 $GameData[$c]["duration"]  = secondsToTime($row["duration"]);
	 $GameData[$c]["datetime"]  = date($DateFormat,strtotime($row["datetime"]));
	 $GameData[$c]["dt"]  = ($row["datetime"]);
	 $GameData[$c]["gamename"]  = ($row["gamename"]);
	 $GameData[$c]["winner"]  = ($row["winner"]);
	 //SET META INFORMATION AND PAGE NAME
	 $HomeTitle = ($row["gamename"]);
	 $HomeDesc = strip_quotes($row["gamename"]);
	 $HomeKeywords = strtolower( strip_quotes($row["gamename"])).','.$HomeKeywords;
	 
	 $db->free($result);
	 
	 //REPLAY
	 $duration = secondsToTime($row["duration"]);
     $replayDate =  strtotime($row["datetime"]);  //3*3600 = +3 HOURS,   +0 minutes.
     $replayDate = date("Y-m-d H:i",$replayDate);
     $gametimenew = substr(str_ireplace(":","-",date("Y-m-d H:i",strtotime($replayDate))),0,16);
	 $gid = $gameid;
	 $gamename = $GameData[$c]["gamename"];
	 require_once('inc/get_replay.php');
	 
	 if ( file_exists($replayloc) ) $GameData[$c]["replay"]  = $replayloc;
	 //END REPLAY
	 
	 $temp_points  = 0;
	 $temp_kills   = 0;
	 $temp_assists = 0;
	 $temp_deaths  = 0;
	 $temp_ck      = 0;
	 $temp_cd      = 0;
	 if ( file_exists("inc/geoip/geoip.inc") ) {
	 include("inc/geoip/geoip.inc");
	 $GeoIPDatabase = geoip_open("inc/geoip/GeoIP.dat", GEOIP_STANDARD);
	 $GeoIP = 1;
	 }
	 
	 $result = $db->query(  getGameInfo($gameid)  );
	 while ($row = $db->fetch_array($result,'assoc')) {
	if ($GeoIP == 1 ) {
	$GameData[$c]["letter"]   = geoip_country_code_by_addr($GeoIPDatabase, $row["ip"]);
	$GameData[$c]["country"]  = geoip_country_name_by_addr($GeoIPDatabase, $row["ip"]);
	}
	if ($GeoIP == 1 AND empty($GameData[$c]["letter"]) ) {
	$GameData[$c]["letter"]  = "blank";
	$GameData[$c]["country"] = "Reserved";
	}
	 
	 $GameData[$c]["heroid"]  = ($row["hero"]);
	 
     $GameData[$c]["kills"]  = ($row["kills"]);
	 $GameData[$c]["deaths"]  = ($row["deaths"]);
	 $GameData[$c]["assists"]  = ($row["assists"]);
	 $GameData[$c]["creepkills"]  = ($row["creepkills"]);
	 $GameData[$c]["creepdenies"]  = ($row["creepdenies"]);
	 $GameData[$c]["neutralkills"]  = ($row["neutralkills"]);
	 $GameData[$c]["towerkills"]  = ($row["towerkills"]);
	 $GameData[$c]["raxkills"]  = ($row["raxkills"]);
	 $GameData[$c]["courierkills"]  = ($row["courierkills"]);
	 $GameData[$c]["spoofedrealm"]  = ($row["spoofedrealm"]);
	 $GameData[$c]["gold"]  = ($row["gold"]);
	 $GameData[$c]["item1"]  = ($row["item1"]);
	 $GameData[$c]["item2"]  = ($row["item2"]);
	 $GameData[$c]["item3"]  = ($row["item3"]);
	 $GameData[$c]["item4"]  = ($row["item4"]);
	 $GameData[$c]["item5"]  = ($row["item5"]);
	 $GameData[$c]["item6"]  = ($row["item6"]);
	 
	 $GameData[$c]["itemname1"]  = strip_quotes($row["itemname1"]);
	 $GameData[$c]["itemname2"]  = strip_quotes($row["itemname2"]);
	 $GameData[$c]["itemname3"]  = strip_quotes($row["itemname3"]);
	 $GameData[$c]["itemname4"]  = strip_quotes($row["itemname4"]);
	 $GameData[$c]["itemname5"]  = strip_quotes($row["itemname5"]);
	 $GameData[$c]["itemname6"]  = strip_quotes($row["itemname6"]);
	 
	 $GameData[$c]["description"]  = strip_quotes($row["description"]);
	 
	 if ( !isset($MostCD)  )       { $MostCD = ($row["name"]); $temp_cd = $row["creepdenies"]; $PlayerCD = $row["creepdenies"]; }
	 if ( !isset($MostCK)  )       { $MostCK = ($row["name"]); $temp_ck = $row["creepkills"]; $PlayerCK = $row["creepkills"]; }
	 if ( !isset($MostDeaths)  )   { $MostDeaths = ($row["name"]); $temp_deaths = $row["deaths"]; $PlayerDeaths = $row["deaths"]; }
	 if ( !isset($MostAssists)  )  { $MostAssists = ($row["name"]); $temp_assists = $row["assists"]; $PlayerAssists = $row["kills"]; }
	 if ( !isset($MostKills)  )    { $MostKills = ($row["name"]); $temp_kills = $row["kills"]; $PlayerKills = $row["kills"]; }
	 if ( !isset($BestPlayer)  )     $BestPlayer = ($row["name"]);
	
	if ( $row["creepdenies"] > $temp_cd ) {
	   $MostCD = ($row["name"]); $PlayerCD = $row["creepdenies"];
	 }
	
	if ( $row["creepkills"] > $temp_ck ) {
	   $MostCK = ($row["name"]); $PlayerCK = $row["creepkills"];
	 }
	
	if ( $row["deaths"] > $temp_deaths ) {
	   $MostDeaths = ($row["name"]); $PlayerDeaths = $row["deaths"];
	 }
	 
	 if ( $row["assists"] > $temp_assists ) {
	   $MostAssists = ($row["name"]); $PlayerAssists = $row["assists"];
	 }
	 
	 if ( $row["kills"] > $temp_kills ) {
	   $MostKills = ($row["name"]); $PlayerKills = $row["kills"];
	 }
	 
	 $score_points = ($row["kills"] -  $row["deaths"]) + ($row["assists"]*0.3);
	 if ( $score_points > $temp_points ) {
	 $BestPlayer = ($row["name"]);
	 $temp_points = $score_points;
	 }
	 
	 if (!empty($row["hero"]) ) $GameData[$c]["hero"]  = ($row["hero"].".$HeroFileExt");
	 else  $GameData[$c]["hero"]  = "blank.gif";
	 
	 if (!empty( $row["itemicon1"] ) ) $GameData[$c]["itemicon1"]  = ($row["itemicon1"]);
	 else $GameData[$c]["itemicon1"] = "empty.gif";
	 
	 if (!empty( $row["itemicon2"] ) ) $GameData[$c]["itemicon2"]  = ($row["itemicon2"]);
	 else $GameData[$c]["itemicon2"] = "empty.gif";
	 if (!empty( $row["itemicon3"] ) ) $GameData[$c]["itemicon3"]  = ($row["itemicon3"]);
	 else $GameData[$c]["itemicon3"] = "empty.gif";
	 if (!empty( $row["itemicon4"] ) ) $GameData[$c]["itemicon4"]  = ($row["itemicon4"]);
	 else $GameData[$c]["itemicon4"] = "empty.gif";
	 if (!empty( $row["itemicon5"] ) ) $GameData[$c]["itemicon5"]  = ($row["itemicon5"]);
	 else $GameData[$c]["itemicon5"] = "empty.gif";
	 if (!empty( $row["itemicon6"] ) ) $GameData[$c]["itemicon6"]  = ($row["itemicon6"]);
	 else $GameData[$c]["itemicon6"] = "empty.gif";
	 
	 $GameData[$c]["left"]  = secondsToTime($row["left"]);
	 $GameData[$c]["leftreason"]  = ($row["leftreason"]);
	 
	 $GameData[$c]["banname"]  = ($row["banname"]);
	 $GameData[$c]["name"]  = ($row["name"]);
	 
	 //CHECK IF USER IS BANNED
	 if ( strtolower($row["name"]) == strtolower($row["banname"]) ) {
	    $GameData[$c]["full_name"]  = '<span class="banned">'.($row["name"])."</span>";
	 } 
	 else 
	 $GameData[$c]["full_name"]  = ($row["name"]);
	 
	 $GameData[$c]["newcolour"]  = ($row["newcolour"]);
	 $GameData[$c]["gameid"]  = ($row["gameid"]);
	 $GameData[$c]["banname"]  = ($row["banname"]);
	 $GameData[$c]["ip"]  = ($row["ip"]);
	 $GameData[$c]["newcolour"]  = ($row["newcolour"]);
	 $c++;
	}
	$db->free($result);	
	if ( isset($GeoIP) AND $GeoIP == 1) geoip_close($GeoIPDatabase);
  }
   // ----- > END SINGLE GAME
  else
   //TOP STATS
   if ( isset( $_GET["top"]) AND $TopPage==1) {
   	 //SET META INFORMATION AND PAGE NAME
	 $HomeTitle = $lang["top"];
	 $HomeDesc = $lang["top"];
	 //$HomeKeywords = strtolower($row["gamename"]).','.$HomeKeywords;
   
   $orderby = "`score` DESC";
   
   if ( isset($_GET["sort"]) ) {
     if ( $_GET["sort"] == "score") $orderby = "`score` DESC";
	 if ( $_GET["sort"] == "player_name") $orderby = "LOWER(`player`) ASC";
	 if ( $_GET["sort"] == "games") $orderby = "(`games`) DESC";
	 if ( $_GET["sort"] == "wins") $orderby = "(`wins`) DESC";
	 if ( $_GET["sort"] == "losses") $orderby = "(`losses`) DESC";
	 if ( $_GET["sort"] == "draw") $orderby = "(`draw`) DESC";
	 if ( $_GET["sort"] == "kills") $orderby = "(`kills`) DESC";
	 if ( $_GET["sort"] == "deaths") $orderby = "(`deaths`) DESC";
	 if ( $_GET["sort"] == "assists") $orderby = "(`assists`) DESC";
	 if ( $_GET["sort"] == "ck") $orderby = "(`creeps`) DESC";
	 if ( $_GET["sort"] == "cd") $orderby = "(`denies`) DESC";
	 if ( $_GET["sort"] == "nk") $orderby = "(`neutrals`) DESC";
   }
   
  $result = $db->query("SELECT COUNT(*) FROM stats WHERE id>=1 LIMIT 1");
  
  $r = $db->fetch_row($result);
  $numrows = $r[0];
  $result_per_page = $TopPlayersPerPage;
  $draw_pagination = 0;
  include('inc/pagination.php');
  $draw_pagination = 1;
  
  $result = $db->query("SELECT * FROM stats WHERE id>=1 ORDER BY $orderby LIMIT $offset, $rowsperpage");
   
  if ( isset($_GET["page"]) AND is_numeric($_GET["page"]) AND $db->num_rows($result) >=1 ) {
     $HomeTitle.=" | Page ".(int) $_GET["page"];
  }
   
   	$c=0;
    $TopData = array();
	$counter = 0;
	
	if ( isset( $_GET["page"]) AND is_numeric($_GET["page"]) ) {
	  $counter = (($_GET["page"]-1) * $TopPlayersPerPage) ;
	}
	
	if ( file_exists("inc/geoip/geoip.inc") ) {
	include("inc/geoip/geoip.inc");
	$GeoIPDatabase = geoip_open("inc/geoip/GeoIP.dat", GEOIP_STANDARD);
	$GeoIP = 1;
	}
	
	while ($row = $db->fetch_array($result,'assoc')) {
	$TopData[$c]["letter"]   = geoip_country_code_by_addr($GeoIPDatabase, $row["ip"]);
	$TopData[$c]["country"]  = geoip_country_name_by_addr($GeoIPDatabase, $row["ip"]);
	if ($GeoIP == 1 AND empty($TopData[$c]["letter"]) ) {
	$TopData[$c]["letter"] = "blank";
	$TopData[$c]["country"] = "Reserved";
	}
	
	$counter++;
	
	$TopData[$c]["counter"]        = $counter;
	$TopData[$c]["id"]        = (int)($row["id"]);
	$TopData[$c]["player"]  = ($row["player"]);

	$TopData[$c]["score"]  = number_format($row["score"],0);
	$TopData[$c]["games"]  = number_format($row["games"],0);
	$TopData[$c]["wins"]  = number_format($row["wins"],0);
	$TopData[$c]["losses"]  = number_format($row["losses"],0);
	$TopData[$c]["draw"]  = number_format($row["draw"],0);
	$TopData[$c]["kills"]  = number_format($row["kills"],0);
	$TopData[$c]["deaths"]  = number_format($row["deaths"],0);
	$TopData[$c]["assists"]  = number_format($row["assists"],0);
	$TopData[$c]["creeps"]  = number_format($row["creeps"],0);
	$TopData[$c]["denies"]  = number_format($row["denies"],0);
	$TopData[$c]["neutrals"]  = number_format($row["neutrals"],0);
	$TopData[$c]["towers"]  = ($row["towers"]);
	$TopData[$c]["rax"]  = ($row["rax"]);
	$TopData[$c]["banned"]  = ($row["banned"]);
	$TopData[$c]["ip"]  = ($row["ip"]);
	
	if ($row["wins"] >0 )
	$TopData[$c]["winslosses"] = ROUND($TopData[$c]["wins"]/($TopData[$c]["wins"]+$TopData[$c]["losses"]), 3)*100;
	else $TopData[$c]["winslosses"] = 0;
		
	//Highlight - sort
	if ( (isset($_GET["sort"]) AND $_GET["sort"] == "score") OR !isset($_GET["sort"]) ) 
	$TopData[$c]["score"] = "<span class='highlight_top'>".$TopData[$c]["score"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "games") 
	$TopData[$c]["games"] = "<span class='highlight_top'>".$TopData[$c]["games"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "wins") 
	$TopData[$c]["wins"] = "<span class='highlight_top'>".$TopData[$c]["wins"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "losses") 
	$TopData[$c]["losses"] = "<span class='highlight_top'>".$TopData[$c]["losses"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "losses") 
	$TopData[$c]["losses"] = "<span class='highlight_top'>".$TopData[$c]["losses"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "draw") 
	$TopData[$c]["draw"] = "<span class='highlight_top'>".$TopData[$c]["draw"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "kills") 
	$TopData[$c]["kills"] = "<span class='highlight_top'>".$TopData[$c]["kills"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "deaths") 
	$TopData[$c]["deaths"] = "<span class='highlight_top'>".$TopData[$c]["deaths"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "assists") 
	$TopData[$c]["assists"] = "<span class='highlight_top'>".$TopData[$c]["assists"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "ck") 
	$TopData[$c]["creeps"] = "<span class='highlight_top'>".$TopData[$c]["creeps"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "cd") 
	$TopData[$c]["denies"] = "<span class='highlight_top'>".$TopData[$c]["denies"]."</span>";
	
	if ( isset($_GET["sort"]) AND $_GET["sort"] == "nk") 
	$TopData[$c]["neutrals"] = "<span class='highlight_top'>".$TopData[$c]["neutrals"]."</span>";
	
	$c++;
	}
	$db->free($result);	
	if ( isset($GeoIP) AND $GeoIP == 1) geoip_close($GeoIPDatabase);
	
   }
   else
   //USER DATA - STATS
   if ( isset( $_GET["u"]) ) {
   
   $uid = safeEscape( (int) $_GET["u"] );
      
	  if ( !is_numeric( $_GET["u"]) ) {
	  $u = safeEscape( $_GET["u"] );
	  
	  $result = $db->query("SELECT * FROM stats WHERE LOWER(player) = LOWER('".$u."') ");
	  
	  if ( $db->num_rows($result)>=1 ) {
	     $row = $db->fetch_array($result,'assoc');
		 $uid = $row["id"];
		 $db->free($result);
		 header("location: ".$website."?u=".$uid.""); die;
	     }
	  }
	  
	$result = $db->query("SELECT s.*, b.name as banname, b.reason, b.admin
	FROM stats as s  
	LEFT JOIN bans as b ON LOWER(b.name) = LOWER(s.player)
	WHERE s.id = '".(int) $uid."' ");
	$c=0;
    $UserData = array();
	
	 if ( file_exists("inc/geoip/geoip.inc") ) {
	 include("inc/geoip/geoip.inc");
	 $GeoIPDatabase = geoip_open("inc/geoip/GeoIP.dat", GEOIP_STANDARD);
	 $GeoIP = 1;
	 }
	
	while ($row = $db->fetch_array($result,'assoc')) {
	
	if ( isset($GeoIP) AND $GeoIP == 1) {
	$UserData[$c]["letter"]   = geoip_country_code_by_addr($GeoIPDatabase, $row["ip"]);
	$UserData[$c]["country"]  = geoip_country_name_by_addr($GeoIPDatabase, $row["ip"]);
	}
	if ($GeoIP == 1 AND empty($UserData[$c]["letter"]) ) {
	$UserData[$c]["letter"] = "blank";
	$UserData[$c]["country"]  = "Reserved";
	}
	
	$UserData[$c]["id"]        = (int)($row["id"]);
	$UserData[$c]["player"]   = ($row["player"]);
	$PlayerName = $UserData[$c]["player"];
	$UserData[$c]["banname"]  = ($row["banname"]);
	$UserData[$c]["reason"]  = ($row["reason"]);
	$UserData[$c]["admin"]  = ($row["admin"]);
	$UserData[$c]["score"]  = number_format($row["score"],0);
	$UserData[$c]["games"]  = number_format($row["games"],0);
	$UserData[$c]["wins"]  = number_format($row["wins"],0);
	$UserData[$c]["losses"]  = number_format($row["losses"],0);
	$UserData[$c]["draw"]  = number_format($row["draw"],0);
	$UserData[$c]["kills"]  = number_format($row["kills"],0);
	$UserData[$c]["deaths"]  = number_format($row["deaths"],0);
	$UserData[$c]["assists"]  = number_format($row["assists"],0);
	$UserData[$c]["creeps"]  = number_format($row["creeps"],0);
	$UserData[$c]["denies"]  = number_format($row["denies"],0);
	$UserData[$c]["neutrals"]  = number_format($row["neutrals"],0);
	$UserData[$c]["towers"]  = ($row["towers"]);
	$UserData[$c]["rax"]  = ($row["rax"]);
	$UserData[$c]["banned"]  = ($row["banned"]);
	$UserData[$c]["ip"]  = ($row["ip"]);
	
	//SET META INFORMATION AND PAGE NAME
	 $HomeTitle = ($row["player"]);
	 $HomeDesc = ($row["player"]);
	 $HomeKeywords = strtolower($row["player"]).','.$HomeKeywords;
	
	if ($row["games"]>=1 AND $row["kills"]>=1) {
	$UserData[$c]["kpm"] = ROUND($row["kills"]/$row["games"],2); 
	}
	else $UserData[$c]["kpm"] = 0;
	
	if ($row["games"]>=1 AND $row["deaths"]>=1) {
	$UserData[$c]["dpm"] = ROUND($row["deaths"]/$row["games"],2); 
	}
	else $UserData[$c]["dpm"] = 0;
	
	if ($row["deaths"]>=1) $UserData[$c]["kd"]  = ROUND($row["kills"] / $row["deaths"],2);
    else $UserData[$c]["kd"] = $row["kills"];
	
	if ($row["wins"] >0 )
	$UserData[$c]["winslosses"] = ROUND($UserData[$c]["wins"]/($UserData[$c]["wins"]+$UserData[$c]["losses"]), 3)*100;
	else $UserData[$c]["winslosses"] = 0;
	$c++;
	}
	$db->free($result);	
	if ( isset($GeoIP) AND $GeoIP == 1) geoip_close($GeoIPDatabase);

    //LONGEST, FASTEST GAME WON
	if ( !empty($PlayerName) AND isset($ShowLongFastGameWon) AND $ShowLongFastGameWon == 1  ) {

	   $LongGame      = $db->query( longGameWon     ( strtolower($PlayerName) )    );
	   $FastGame      = $db->query( fastGameWon     ( strtolower($PlayerName) )    );
	   $GamesDuration = $db->query( GetGameDurations( strtolower($PlayerName) )    );
	   
	   $lg = $db->fetch_array($LongGame,'assoc');
	   $fg = $db->fetch_array($FastGame,'assoc');
	   $dg = $db->fetch_array($FastGame,'assoc');
	   
	   $LongestGame = array();
	   $FastestGame = array();
	   $Durations   = array();
	   
	   $LongestGame["gameid"] = ($lg["gameid"]);
	   $LongestGame["gamename"] = ($lg["gamename"]);
	   $LongestGame["duration"] = secondsToTime($lg["duration"]);
	   $LongestGame["kills"] = ($lg["kills"]);
	   $LongestGame["deaths"] = ($lg["deaths"]);
	   $LongestGame["assists"] = ($lg["assists"]);
	   $LongestGame["creepkills"] = ($lg["creepkills"]);
	   $LongestGame["creepdenies"] = ($lg["creepdenies"]);
	   $LongestGame["neutralkills"] = ($lg["neutralkills"]);
	   $LongestGame["newcolour"] = ($lg["newcolour"]);
	   
	   $FastestGame["gameid"] = ($fg["gameid"]);
	   $FastestGame["gamename"] = ($fg["gamename"]);
	   $FastestGame["duration"] = secondsToTime($fg["duration"]);
	   $FastestGame["kills"] = ($fg["kills"]);
	   $FastestGame["deaths"] = ($fg["deaths"]);
	   $FastestGame["assists"] = ($fg["assists"]);
	   $FastestGame["creepkills"] = ($fg["creepkills"]);
	   $FastestGame["creepdenies"] = ($fg["creepdenies"]);
	   $FastestGame["neutralkills"] = ($fg["neutralkills"]);
	   $FastestGame["newcolour"] = ($fg["newcolour"]);
	   
	   $Durations["min_loading"] = $dg["MIN(loadingtime)"];
	   $Durations["max_loading"] = $dg["MAX(loadingtime)"];
	   $Durations["avg_loading"] = $dg["AVG(loadingtime)"];
	   //$Durations["avg_loading"] = $dg["AVG(loadingtime)"];
	   
         //GET MOST PLAYED HERO BY USER
	     $getHero = $db->query( GetMostPlayedHero( $PlayerName ) );
	     $row = $db->fetch_array($getHero,'assoc');
	     $FavoriteHero = array();
	     $TimePlayed["timeplayed"] = secondsToTime($row["timeplayed"], $lang["h"], $lang["m"], $lang["s"]);
	     $FavoriteHero["original"] = $row["original"];
	     $FavoriteHero["description"] = $row["description"];
		 $FavoriteHero["played"] = $row["played"];
	     $db->free($result);
         if ( isset($ShowUserHeroStats ) AND $ShowUserHeroStats ==1 ) {
		 //GET MOST KILLS HERO BY USER
	     $getHero = $db->query( GetMostKillsHero( $PlayerName ) );
	     $row = $db->fetch_array($getHero,'assoc');
	     $MostKillsHero = array();
	     $MostKillsHero["kills"] = ($row["maxkills"]);
		 $MostKillsHero["gameid"] = ($row["gameid"]);
	     $MostKillsHero["original"] = $row["original"];
	     $MostKillsHero["description"] = $row["description"];
	     $db->free($result);
		 //GET MOST DEATHS HERO BY USER
	     $getHero = $db->query( GetMostDeathsHero( $PlayerName ) );
	     $row = $db->fetch_array($getHero,'assoc');
	     $MostDeathsHero = array();
		 $MostDeathsHero["gameid"] = ($row["gameid"]);
	     $MostDeathsHero["deaths"] = ($row["maxdeaths"]);
	     $MostDeathsHero["original"] = $row["original"];
	     $MostDeathsHero["description"] = $row["description"];
	     $db->free($result);
		 //GET MOST Assists HERO BY USER
	     $getHero = $db->query( GetMostAssistsHero( $PlayerName ) );
	     $row = $db->fetch_array($getHero,'assoc');
	     $MostAssistsHero = array();
		 $MostAssistsHero["gameid"] = ($row["gameid"]);
	     $MostAssistsHero["assists"] = ($row["maxassists"]);
	     $MostAssistsHero["original"] = $row["original"];
	     $MostAssistsHero["description"] = $row["description"];
	     $db->free($result);
		 //GET MOST WINS HERO BY USER
	     $getHero = $db->query( GetMostWinsHero( $PlayerName ) );
	     $row = $db->fetch_array($getHero,'assoc');
	     $MostWinsHero = array();
	     $MostWinsHero["wins"] = ($row["wins"]);
	     $MostWinsHero["original"] = $row["original"];
	     $MostWinsHero["description"] = $row["description"];
	     $db->free($result);
		 
		 
	     }
	   }
	
   } //END OF USER DATA	
   
   //SEARCH 
   
   if ( isset($_GET["search"]) AND strlen($_GET["search"])>=2  ) {
      $s = safeEscape( $_GET["search"]);
	  $result = $db->query("SELECT COUNT(*) FROM stats WHERE LOWER(player) LIKE LOWER('%".$s."%') LIMIT 1");
	  $r = $db->fetch_row($result);
	  $numrows = $r[0];
	  $result_per_page = $TopPlayersPerPage;
	  $draw_pagination = 0;
	  include('inc/pagination.php');
	  $draw_pagination = 1;
	  
	  
	  $result = $db->query("SELECT * FROM stats WHERE LOWER(player) LIKE LOWER('%".$s."%') 
	  ORDER BY score DESC
	  LIMIT $offset, $rowsperpage");
	  
	$c=0;
    $SearchData = array();
	if ( file_exists("inc/geoip/geoip.inc") ) {
	include("inc/geoip/geoip.inc");
	$GeoIPDatabase = geoip_open("inc/geoip/GeoIP.dat", GEOIP_STANDARD);
	$GeoIP = 1;
	}
	while ($row = $db->fetch_array($result,'assoc')) {
	if ( isset($GeoIP) AND $GeoIP == 1) {
	$SearchData[$c]["letter"]   = geoip_country_code_by_addr($GeoIPDatabase, $row["ip"]);
	$SearchData[$c]["country"]  = geoip_country_name_by_addr($GeoIPDatabase, $row["ip"]);
	}
	if ($GeoIP == 1 AND empty($SearchData[$c]["letter"]) ) { 
	$SearchData[$c]["letter"] = "blank";
	$SearchData[$c]["country"]  = "Reserved";
	}
	$SearchData[$c]["id"]        = (int)($row["id"]);
	$SearchData[$c]["player"]  = ($row["player"]);
	$SearchData[$c]["score"]  = number_format($row["score"],0);
	$SearchData[$c]["games"]  = number_format($row["games"],0);
	$SearchData[$c]["wins"]  = number_format($row["wins"],0);
	$SearchData[$c]["losses"]  = number_format($row["losses"],0);
	$SearchData[$c]["draw"]  = number_format($row["draw"],0);
	$SearchData[$c]["kills"]  = number_format($row["kills"],0);
	$SearchData[$c]["deaths"]  = number_format($row["deaths"],0);
	$SearchData[$c]["assists"]  = number_format($row["assists"],0);
	$SearchData[$c]["creeps"]  = number_format($row["creeps"],0);
	$SearchData[$c]["denies"]  = number_format($row["denies"],0);
	$SearchData[$c]["neutrals"]  = number_format($row["neutrals"],0);
	$SearchData[$c]["towers"]  = ($row["towers"]);
	$SearchData[$c]["rax"]  = ($row["rax"]);
	$SearchData[$c]["banned"]  = ($row["banned"]);
	$SearchData[$c]["ip"]  = ($row["ip"]);
	
	$c++;
	}
	if ( isset($GeoIP) AND $GeoIP == 1) geoip_close($GeoIPDatabase);
	
	$db->free($result);	
	
   }
   
   //BANS
   if ( isset($_GET["bans"]) AND $BansPage == 1) {
   
   	 $HomeTitle = $lang["bans"] ;
	 $HomeDesc = $lang["bans"];
	 $HomeKeywords = strtolower( strip_quotes($lang["bans"])).','.$HomeKeywords;
   
     if ( isset($_GET["search_bans"]) AND strlen($_GET["search_bans"])>=2  ) {
	    $search_bans = safeEscape( $_GET["search_bans"]);
		$sql = "AND LOWER(name) LIKE LOWER('%".$search_bans."%') ";
	 } else $sql = "";
   
     $result = $db->query("SELECT COUNT(*) FROM bans WHERE id>=1 $sql LIMIT 1");
	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = $TopPlayersPerPage;
	 $draw_pagination = 0;
	 include('inc/pagination.php');
	 $draw_pagination = 1;
	  
	 $result = $db->query("SELECT * FROM bans WHERE id>=1 $sql ORDER BY id DESC LIMIT $offset, $rowsperpage");
	 
	 $c=0;
    $BansData = array();
	if ( file_exists("inc/geoip/geoip.inc") ) {
	include("inc/geoip/geoip.inc");
	$GeoIPDatabase = geoip_open("inc/geoip/GeoIP.dat", GEOIP_STANDARD);
	$GeoIP = 1;
	}
	while ($row = $db->fetch_array($result,'assoc')) {
	if ( isset($GeoIP) AND $GeoIP == 1) {
	$BansData[$c]["letter"]   = geoip_country_code_by_addr($GeoIPDatabase, $row["ip"]);
	$BansData[$c]["country"]  = geoip_country_name_by_addr($GeoIPDatabase, $row["ip"]);
	}
	if ($GeoIP == 1 AND empty($BansData[$c]["letter"]) ) {
	$BansData[$c]["letter"] = "blank";
	$BansData[$c]["country"]  = "Reserved";
	}
	
	$BansData[$c]["id"]        = (int)($row["id"]);
	$BansData[$c]["server"]  = ($row["server"]);
	$BansData[$c]["name"]  = ($row["name"]);
	$BansData[$c]["ip"]  = ($row["ip"]);
	$BansData[$c]["date"]  = date($DateFormat, strtotime($row["date"]));
	$BansData[$c]["gamename"]  = ($row["gamename"]);
	$BansData[$c]["admin"]  = ($row["admin"]);
	$BansData[$c]["reason"]  = substr(stripslashes($row["reason"]),0, 30);
	$BansData[$c]["reason_full"]  = ($row["reason"]);
	if ( empty($BansData[$c]["reason"]) )   $BansData[$c]["reason"] = '&nbsp;';
	if ( empty($BansData[$c]["gamename"]) ) $BansData[$c]["gamename"] = '&nbsp;';
	//$BansData[$c]["expiredate"]  = ($row["expiredate"]);
	//$BansData[$c]["warn"]  = ($row["warn"]);
	$c++;
	}
	if ( isset($GeoIP) AND $GeoIP == 1) geoip_close($GeoIPDatabase);
	
	$db->free($result);	
   
   }
   
   //A D M I N S
   
   if ( isset( $_GET["admins"]) AND $AdminsPage == 1 ) {
   
     $HomeTitle = $lang["admins"] ;
	 $HomeDesc = $lang["admins"];
	 $HomeKeywords = strtolower( strip_quotes($lang["admins"])).','.$HomeKeywords;
    
	 $result = $db->query("SELECT COUNT(*) FROM admins WHERE id>=1 LIMIT 1");
	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = $TopPlayersPerPage;
	 $draw_pagination = 0;
	 include('inc/pagination.php');
	 $draw_pagination = 1;
	 
	 $c=0;
    $AdminsData = array();
	
	$result = $db->query("SELECT * FROM admins WHERE id>=1 ORDER BY id DESC LIMIT $offset, $rowsperpage");
	
	while ($row = $db->fetch_array($result,'assoc')) {
	$AdminsData[$c]["id"]        = (int)($row["id"]);
	$AdminsData[$c]["name"]  = ($row["name"]);
	$AdminsData[$c]["server"]  = ($row["server"]);
	$c++;
	}
	$db->free($result);	
    
   }
   
   //Torneo DotA
   if ( isset( $_GET["dota"]) ) {
     $HomeTitle = $lang["dota"] ;
	 $HomeDesc = $lang["dota"];
	 $HomeKeywords = strtolower( strip_quotes($lang["dota"])).','.$HomeKeywords;
    
	 $result = $db->query("SELECT COUNT(*) FROM torneos WHERE id>=1 LIMIT 1");
	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = 100;
	 $draw_pagination = 0;
	 include('inc/pagination.php');
	 $draw_pagination = 0;
	 
	 $c=0;
    $DotAData = array();
	
	$result = $db->query("SELECT * FROM torneos WHERE dota=1 ORDER BY puntos DESC LIMIT $offset, $rowsperpage");
	
	while ($row = $db->fetch_array($result,'assoc')) {
	$DotAData[$c]["name"]  = ($row["name"]);
	$DotAData[$c]["puntos"]  = ($row["puntos"]);
	$DotAData[$c]["torneos_jugados"]  = ($row["torneos_jugados"]);
	$c++;
	}
	$db->free($result);	
	}
	
	//Torneo PG
   if ( isset( $_GET["pg"]) ) {
     $HomeTitle = $lang["pg"] ;
	 $HomeDesc = $lang["pg"];
	 $HomeKeywords = strtolower( strip_quotes($lang["pg"])).','.$HomeKeywords;
    
	 $result = $db->query("SELECT COUNT(*) FROM torneos WHERE id>=1 LIMIT 1");
	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = 100;
	 $draw_pagination = 0;
	 include('inc/pagination.php');
	 $draw_pagination = 0;
	 
	 $c=0;
    $DotAData = array();
	
	$result = $db->query("SELECT * FROM torneos WHERE dota=0 ORDER BY puntos DESC LIMIT $offset, $rowsperpage");
	
	while ($row = $db->fetch_array($result,'assoc')) {
	$DotAData[$c]["name"]  = ($row["name"]);
	$DotAData[$c]["puntos"]  = ($row["puntos"]);
	$DotAData[$c]["torneos_jugados"]  = ($row["torneos_jugados"]);
	$c++;
	}
	$db->free($result);	
	}
	
   //WARN
   if ( isset($_GET["warn"]) AND $WarnPage == 1) {
   
    $HomeTitle = $lang["warn"] ;
	$HomeDesc = $lang["warn"];
	$HomeKeywords = strtolower( strip_quotes($lang["warn"])).','.$HomeKeywords;
   
     if ( isset($_GET["search_bans"]) AND strlen($_GET["search_bans"])>=2  ) {
	    $search_bans = safeEscape( $_GET["search_bans"]);
		$sql = "AND LOWER(name) LIKE LOWER('%".$search_bans."%') ";
	 } else $sql = "";
   
     $result = $db->query("SELECT COUNT(*) FROM bans WHERE id>=1 AND warn = 1 $sql LIMIT 1");
	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = $TopPlayersPerPage;
	 $draw_pagination = 0;
	 include('inc/pagination.php');
	 $draw_pagination = 1;
	  
	 $result = $db->query("SELECT * FROM bans WHERE id>=1 $sql AND warn = 1 LIMIT $offset, $rowsperpage");
	 
	 $c=0;
    $BansData = array();
	if ( file_exists("inc/geoip/geoip.inc") ) {
	include("inc/geoip/geoip.inc");
	$GeoIPDatabase = geoip_open("inc/geoip/GeoIP.dat", GEOIP_STANDARD);
	$GeoIP = 1;
	}
	while ($row = $db->fetch_array($result,'assoc')) {
	if ( isset($GeoIP) AND $GeoIP == 1)
	$BansData[$c]["letter"]   = geoip_country_code_by_addr($GeoIPDatabase, $row["ip"]);
	if ($GeoIP == 1 AND empty($BansData[$c]["letter"]) ) $BansData[$c]["letter"] = "blank";
	$BansData[$c]["id"]        = (int)($row["id"]);
	$BansData[$c]["server"]  = ($row["server"]);
	$BansData[$c]["name"]  = ($row["name"]);
	$BansData[$c]["ip"]  = ($row["ip"]);
	$BansData[$c]["date"]  = date($DateFormat, strtotime($row["date"]));
	$BansData[$c]["gamename"]  = ($row["gamename"]);
	$BansData[$c]["admin"]  = ($row["admin"]);
	$BansData[$c]["reason"]  = substr($row["reason"],0, 40);
	$BansData[$c]["reason_full"]  = ($row["reason"]);
	//$BansData[$c]["expiredate"]  = ($row["expiredate"]);
	//$BansData[$c]["warn"]  = ($row["warn"]);
	$c++;
	}
	if ( isset($GeoIP) AND $GeoIP == 1) geoip_close($GeoIPDatabase);
	
	$db->free($result);	
   
   }
   
   
   
   //SAFELIST
   if ( isset($_GET["safelist"]) AND $SafelistPage == 1) {
   
    $HomeTitle = $lang["safelist"] ;
	$HomeDesc = $lang["safelist"];
	$HomeKeywords = strtolower( strip_quotes($lang["safelist"])).','.$HomeKeywords;

     $result = $db->query("SELECT COUNT(*) FROM  safelist WHERE id>=1 LIMIT 1");
	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = $TopPlayersPerPage;
	 $draw_pagination = 0;
	 include('inc/pagination.php');
	 $draw_pagination = 1;
	  
	 $result = $db->query("SELECT * FROM  safelist WHERE id>=1 LIMIT $offset, $rowsperpage");
	 
	 $c=0;
     $SafelistData = array();

	while ($row = $db->fetch_array($result,'assoc')) {
	$SafelistData[$c]["id"]        = (int)($row["id"]);
	$SafelistData[$c]["server"]  = ($row["server"]);
	$SafelistData[$c]["name"]  = ($row["name"]);
	$SafelistData[$c]["voucher"]  = ($row["voucher"]);
	$c++;
	}	
	$db->free($result);	
   
   }
   
   //HEROES
   if ( isset($_GET["heroes"]) ) {
   
    $HomeTitle = $lang["heroes"] ;
	$HomeDesc = $lang["heroes"];
	$HomeKeywords = strtolower( strip_quotes($lang["heroes"])).','.$HomeKeywords;
   
    if ( isset($_GET["search_heroes"]) AND strlen($_GET["search_heroes"])>=2  ) {
	    $search_heroes = safeEscape( $_GET["search_heroes"]);
		$sql = "AND LOWER(description) LIKE LOWER('%".$search_heroes."%') ";
	 } else $sql = ""; 
   
   
   $result = $db->query("SELECT COUNT(*) FROM heroes WHERE summary!= '-' $sql LIMIT 1");
   	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = $HeroesPerPage;
	 $draw_pagination = 0;
	 $total_comments  = $numrows;
	 include('inc/pagination.php');
	 $draw_pagination = 1;
	 
	 $result = $db->query("SELECT * FROM heroes WHERE summary!= '-' $sql ORDER BY LOWER(description) ASC LIMIT $offset, $rowsperpage");
	 $c=0;
     $HeroesData = array();
	 
	while ($row = $db->fetch_array($result,'assoc')) {
	$HeroesData[$c]["id"]        = (int)($row["heroid"]);
	$HeroesData[$c]["original"]  = ($row["original"]);
	$HeroesData[$c]["description"]  = ($row["description"]);
	$HeroesData[$c]["summary"]  = ($row["summary"]);
	$c++;
	}	
	$db->free($result);	
   }  
   
   
   //SINGLE HERO
   if ( isset($_GET["hero"]) ) {
    $heroid = safeEscape( $_GET["hero"] );
	$pdHero = get_HeroByID($heroid);
	$hero = str_replace("-"," ",strtoupper($pdHero));
	
	//get hero data from playdota website
	if ($PlayDotaHeroes == 1) {
	 if ( !file_exists("inc/cache/pdheroes/".$pdHero.".html") ) include('inc/PlayDotaHeroParser.php');
	 }
	  else {
	 //get hero data from database
	 $result = $db->query("SELECT * FROM heroes WHERE heroid = '".$heroid."' LIMIT 1");
	 $c=0;
     $HeroData = array();
	 $row = $db->fetch_array($result,'assoc');
	 $HeroData[$c]["id"]        = (int)($row["heroid"]);
	 $HeroData[$c]["original"]  = ($row["original"]);
	 $HeroData[$c]["description"]  = ($row["description"]);
	 $HeroData[$c]["summary"]  = convEnt($row["summary"]);
	 $HeroData[$c]["stats"]  = convEnt($row["stats"]);
	 $HeroData[$c]["skills"]  = convEnt($row["skills"]);
	 
	$HomeTitle = ($row["description"]);
	$HomeDesc = strip_quotes($row["summary"]);
	$HomeKeywords = strtolower( strip_quotes($row["description"])).','.$HomeKeywords;
	 }
	 
   }
   
   //ITEMS 
   if ( isset($_GET["items"]) ) {
   
    $HomeTitle = $lang["items"] ;
	$HomeDesc = $lang["items"];
	$HomeKeywords = strtolower( strip_quotes($lang["items"])).','.$HomeKeywords;
   
    if ( isset($_GET["search_items"]) AND strlen($_GET["search_items"])>=2  ) {
	    $search_items = safeEscape( $_GET["search_items"]);
		$sql = "AND LOWER(name) LIKE LOWER('%".$search_items."%') ";
	 } else $sql = ""; 
	 
    if ( isset($_GET["search_items"]) AND strlen($_GET["search_items"])>=2  ) {
	$result = $db->query("SELECT * FROM items as Items
	WHERE item_info !='' AND name != 'Aegis Check' 
	AND name != 'Arcane Ring' AND name NOT LIKE 'Disabled%' $sql
	GROUP BY LOWER(shortname) 
	ORDER BY LOWER(shortname) ASC");
	
	$numrows = $db->num_rows($result);
	
	} else {
    $result = $db->query("SELECT COUNT(*)  FROM items WHERE item_info !='' AND name != 'Aegis Check' 
	AND name != 'Arcane Ring' AND name NOT LIKE 'Disabled%' $sql LIMIT 1");
	$r = $db->fetch_row($result);
	$numrows = $r[0];
	}
	$result_per_page = $ItemsPerPage;
	$draw_pagination = 0;
	//$total_comments  = $numrows;
	include('inc/pagination.php');
	$draw_pagination = 1;

	$result = $db->query("SELECT * FROM items as Items
	WHERE item_info !='' AND name != 'Aegis Check' 
	AND name != 'Arcane Ring' AND name NOT LIKE 'Disabled%' $sql
	GROUP BY LOWER(shortname) 
	ORDER BY LOWER(shortname) ASC 
	LIMIT $offset, $rowsperpage");
	
	//if ($db->num_rows() )
	
	$c=0;
    $ItemsData = array();
	 
	while ($row = $db->fetch_array($result,'assoc')) {
	$ItemsData[$c]["itemid"]  = ($row["itemid"]);
	$ItemsData[$c]["name"]  = ($row["name"]);
	$ItemsData[$c]["shortname"]  = ($row["shortname"]);
	$ItemsData[$c]["item_info"]  = convEnt($row["item_info"]);
	$ItemsData[$c]["icon"]  = ($row["icon"]);
	$c++;
	}
	$db->free($result);	
   }
   
   //SINGLE ITEM
   if ( isset($_GET["item"]) ) {
    $itemID = safeEscape( $_GET["item"] ) ;
	$result = $db->query("SELECT * FROM items WHERE itemid = '".$itemID."' ");
	
	$c=0;
    $ItemData = array();
	
	$row = $db->fetch_array($result,'assoc');
	$ItemData[$c]["itemid"]  = ($row["itemid"]);
	$ItemData[$c]["name"]  = ($row["name"]);
	$ItemData[$c]["shortname"]  = ($row["shortname"]);
	$ItemData[$c]["item_info"]  = convEnt($row["item_info"]);
	$ItemData[$c]["itemid"]  = ($row["itemid"]);
	$ItemData[$c]["icon"]  = ($row["icon"]);
	$c++;	
	
    $HomeTitle = $row["shortname"] ;
	$HomeDesc = strip_tags(strip_quotes($row["item_info"]));
	$HomeDesc = str_replace("\n", " ", limit_words($HomeDesc, 42) );
	$HomeKeywords = strtolower( strip_quotes($row["shortname"])).','.$HomeKeywords;
	
	$db->free($result);	
	}
   
   //HOME PAGE
   if ( !$_GET OR ( isset($_GET["post_id"])  OR (!isset($_GET["u"]) AND isset($_GET["page"])  ) ) 
   AND !isset($_GET["games"]) 
   AND !isset($_GET["heroes"])  
   AND !isset($_GET["items"])
   AND !isset($_GET["warn"])
   AND !isset($_GET["safelist"])
   AND !isset($_GET["ban_appeals"])
   AND !isset($_GET["ban_reports"])
   AND !isset($_GET["admins"])
   AND !isset($_GET["about_us"])
   AND !isset($_GET["top"])
                            ) 
   {
   
     $HOME_PAGE = 1;
	 
	 if ( isset($_GET["post_id"]) AND is_numeric($_GET["post_id"]) ) {
	 
	 $id = safeEscape( (int) $_GET["post_id"]);
	 $SinglePost = 1;
	 $sql = " AND news_id = '".$id."' ";
	//GET COMMENTS
	 $result = $db->query("SELECT COUNT(*) FROM comments WHERE post_id='".$id."'");
	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = $CommentsPerPage;
	 $draw_pagination = 0;
	 $total_comments  = $numrows;
	 include('inc/pagination.php');
	 $draw_pagination = 1;
	 
	 $CommentOrder = "id DESC";
	 
	  $result = $db->query("SELECT c.*, u.user_name, u.user_fbid, u.user_avatar, u.user_website, u.user_gender, u.user_level, u.phpbb_id, u.smf_id
	  FROM  comments as c
	  LEFT JOIN users as u ON u.user_id = c.user_id
	  WHERE c.post_id='".$id."' ORDER BY c.$CommentOrder LIMIT $offset, $rowsperpage");
	  $c=0;
     $CommentsData = array();
	 
	while ($row = $db->fetch_array($result,'assoc')) {
	$CommentsData[$c]["id"]        = (int)($row["id"]);
	$CommentsData[$c]["username"]  = ($row["user_name"]);
	$CommentsData[$c]["user_id"]  = ($row["user_id"]);
	$CommentsData[$c]["post_id"]  = ($row["post_id"]);
	$CommentsData[$c]["text"]  = convEnt($row["text"]);
	if (isset($AutoLinkComments) AND $AutoLinkComments == 2)
	$CommentsData[$c]["text"]  = RemoveLinks( $row["text"], $AutoLinkTextReplace  );
	else
	if (isset($AutoLinkComments) AND $AutoLinkComments == 1)
	$CommentsData[$c]["text"]  = AutoLinkShort( $row["text"], 'target="_blank" class="u_links"' );
	else 
	if (isset($AutoLinkComments) AND $AutoLinkComments == 1 AND isset($AutoLinkFull) AND $AutoLinkFull == 1)
	$CommentsData[$c]["text"]  = AutoLinkFull( $row["text"], 'target="_blank" class="u_links"' );
	
	$CommentsData[$c]["date"]  = date($DateFormat, $row["date"]);
	$CommentsData[$c]["user_ip"]  = ($row["user_ip"]);
	$CommentsData[$c]["fb"]  = ($row["user_fbid"]);
	$CommentsData[$c]["avatar"]  = ($row["user_avatar"]);
	if (empty($row["user_avatar"]) ) $CommentsData[$c]["avatar"] = $website."img/avatar_64.png";
	$CommentsData[$c]["website"]  = ($row["user_website"]);
	$CommentsData[$c]["gender"]  = ($row["user_gender"]);
	$CommentsData[$c]["post_id"]  = ($row["post_id"]);
	$CommentsData[$c]["user_level"]  = ($row["user_level"]);
	$CommentsData[$c]["phpbb_id"]  = ($row["phpbb_id"]);
	$CommentsData[$c]["smf_id"]  = ($row["smf_id"]);
	$c++;
	}	
	$db->free($result);	
		
		
	 } else $sql = "";
	 
	 $result = $db->query("SELECT COUNT(*) FROM news WHERE news_id>=1 $sql LIMIT 1");
	 $r = $db->fetch_row($result);
	 $numrows = $r[0];
	 $result_per_page = $NewsPerPage;
	 $draw_pagination = 0;
	 include('inc/pagination.php');
	 $draw_pagination = 1;
	 
	 $result = $db->query("SELECT * FROM  news WHERE news_id>=1 AND status=1 $sql ORDER BY news_id DESC 
	 LIMIT $offset, $rowsperpage");
	 $c=0;
     $NewsData = array();
	 
	while ($row = $db->fetch_array($result,'assoc')) {
	
	if ( isset($_GET["post_id"]) AND is_numeric($_GET["post_id"]) ) {
	$HomeTitle = ($row["news_title"]);
	$HomeDesc = limit_words( convEnt( $row["news_content"]), 15);
	$HomeDesc =removeDoubleSpaces($HomeDesc);
	$HomeKeywords = AutoKeywords($row["news_title"]).','.$HomeKeywords;
	$CommentsAllowed = $row["allow_comments"];
	
	if ( !isset($updateViews) ) 
	$updateViews = $db->query("UPDATE news SET views = views+1 WHERE news_id = '".$row["news_id"]."' LIMIT 1");
	
	}
	
	$NewsData[$c]["id"]        = (int)($row["news_id"]);
	$NewsData[$c]["title"]  = ($row["news_title"]);
	$NewsData[$c]["text"]  = convEnt($row["news_content"]);
	//$NewsData[$c]["text"]  = str_replace("\n","<br />", $NewsData[$c]["text"]);
	$NewsData[$c]["date"]  = ($row["news_date"]);
	$NewsData[$c]["comments"]  = ($row["comments"]);
	$NewsData[$c]["allow_comments"]  = ($row["allow_comments"]);
	$c++;
	}	
	$db->free($result);	
	
    //RECENT GAMES
	if ( $RecentGames == 1 AND !isset($_GET["post_id"]) AND !isset($_GET["page"]) ) {
    $result = $db->query( getAllGames($MinDuration, 0, $TotalRecentGames )  );
	$c=0;
	
    $RecentGamesData = array();
	while ($row = $db->fetch_array($result,'assoc')) {
	$RecentGamesData[$c]["id"]        = (int)($row["id"]);
	$RecentGamesData[$c]["map"]  = convEnt2(substr($row["map"], strripos($row["map"], '\\')+1));
	$RecentGamesData[$c]["map"] = reset( explode(".w", $RecentGamesData[$c]["map"] ) );
	$RecentGamesData[$c]["map"] = substr($RecentGamesData[$c]["map"],0,20);
	$RecentGamesData[$c]["datetime"]  = ($row["datetime"]);
	$RecentGamesData[$c]["gamename"]  = ($row["gamename"]);
	$RecentGamesData[$c]["ownername"]  = ($row["ownername"]);
	$RecentGamesData[$c]["duration"]  = ($row["duration"]);
	$RecentGamesData[$c]["creatorname"]  = ($row["creatorname"]);
	$RecentGamesData[$c]["winner"]  = ($row["winner"]);
	$RecentGamesData[$c]["type"]  = ($row["type"]);
	
	//REPLAY
	 $duration = secondsToTime($row["duration"]);
     $replayDate =  strtotime($row["datetime"]);  //3*3600 = +3 HOURS,   +0 minutes.
     $replayDate = date("Y-m-d H:i",$replayDate);
     $gametimenew = substr(str_ireplace(":","-",date("Y-m-d H:i",strtotime($replayDate))),0,16);
	 $gid =  (int)($row["id"]);
	 $gamename = $RecentGamesData[$c]["gamename"];
	 include('inc/get_replay.php');
	 
	 if ( file_exists($replayloc) ) $RecentGamesData[$c]["replay"] = $replayloc; 
	 else $RecentGamesData[$c]["replay"] = "";
	 //END REPLAY
	$c++;
	}	
	$db->free($result);	
	}
   } 
   
   //USER PROFILE
   if ( isset($_GET["profile"]) AND is_logged() ) {
   
   if ( isset($_POST["change_profile"]) ) {
      $avatar = EscapeStr( trim($_POST["avatar"]));
	  $location = safeEscape( trim($_POST["location"]));
	  $realm = safeEscape( trim($_POST["realm"]));
	  $www = EscapeStr( trim($_POST["website"]));
	  $gender = EscapeStr( trim($_POST["gender"]));
	  
	  $sql = "UPDATE users SET ";
	  
	  if ( is_valid_url($avatar) OR empty($avatar) )   $sql.="user_avatar = '".$avatar."', ";
	  //if ( strlen($location)>=3 )                
	  $sql.="user_location = '".$location."', ";
	  //if ( strlen($realm)>=3 )                   
	  $sql.="user_realm = '".$realm."', ";
	  if ( is_valid_url($www) OR empty($www) )         $sql.="user_website = '".$www."', ";
	  
	  if ( isset($_POST["pw_confirm"]) AND $_POST["pw_confirm"] == 1 ) {
	    $pass1 = $_POST["pw_1"];
		$pass2 = $_POST["pw_2"];
		
		if ( $pass1 == $pass2 ) $pwchange = 2; //Passwords not same
		if ( strlen($pass1)<3 ) $pwchange = 3; // Password have too few characters
		
		if ( $pass1 == $pass2 AND strlen($pass1)>=3 ) {
		   	$hash = generate_hash(16,1);
	     	$password_db = generate_password($pass2, $hash);
			$sql.="user_password = '".$password_db."', password_hash = '".$hash."', ";
			$pwchange = 1; //Password successfully changed
		}
	  }
	  
	  if ( $gender == 1) $gen = 1; else if ( $gender == 2) $gen = 2; else $gen = 0;
	  $sql.="user_gender = '".$gen."' ";
	  
	  $sql.=" WHERE user_name = '".$_SESSION["username"]."' ";
	  
	  $update = $db->query($sql);
	  
	  if ( isset($pwchange) ) { header('location: '.$website.'?profile&pwchange='.$pwchange); die; }
	  
	  header('location: '.$website.'?profile&updated'); die;
   }
   
   
      $c=0;
	  $ProfileData = array();
      $id = safeEscape( (int) $_SESSION["user_id"] );
	  $result = $db->query("SELECT * FROM users WHERE user_id = '".(int) $id."' AND code = ''");
	  $row = $db->fetch_array($result,'assoc');
	  
	  $ProfileData[$c]["id"]        = (int)($row["user_id"]);
	  $ProfileData[$c]["user_name"]  = ($row["user_name"]);
	  $ProfileData[$c]["user_email"]  = ($row["user_email"]);
	  $ProfileData[$c]["user_joined"]  = ($row["user_joined"]);
	  $ProfileData[$c]["user_level"]  = ($row["user_level"]);
	  $ProfileData[$c]["user_last_login"]  = ($row["user_last_login"]);
	  $ProfileData[$c]["user_ip"]  = ($row["user_ip"]);
	  $ProfileData[$c]["user_avatar"]  = ($row["user_avatar"]);
	  $ProfileData[$c]["user_location"]  = ($row["user_location"]);
	  $ProfileData[$c]["user_realm"]  = ($row["user_realm"]);
	  $ProfileData[$c]["user_website"]  = ($row["user_website"]);
	  $ProfileData[$c]["user_gender"]  = ($row["user_gender"]);
	  $ProfileData[$c]["user_fbid"]  = ($row["user_fbid"]);
	  $ProfileData[$c]["can_comment"]  = ($row["can_comment"]);
	  
	  $db->free($result);	
   }
   
   //BAN REPORT
   if ( isset($_GET["ban_report"]) AND $BanReports == 1) {
      
	  if (isset($_POST["submit_report"]) ) {
	     $player = safeEscape(trim($_POST["report_player"]));
		 $subject = safeEscape(trim($_POST["subject"]));
		 $reason = safeEscape(trim($_POST["message"]));
		 $reason = my_nl2br( trim($_POST["message"]) );
		 $reason = nl2br($reason);
		 $reason = EscapeStr( ($reason) );
		 $game_url   = EscapeStr(trim($_POST["game_url"]));
		 $replay_url = EscapeStr(trim($_POST["replay_url"]));
		 $errors = "";
		 
		 if ( strlen($player)<=2 )  $errors.="<div>".$lang["error_report_player"]."</div>";
		 if ( strlen($subject)<=2 ) $errors.="<div>".$lang["error_report_subject"]."</div>";
		 if ( strlen($reason)<=2 )  $errors.="<div>".$lang["error_report_reason"]."</div>";
		 if ( !is_logged() )  $errors ="<div>".$lang["error_report_login"]."</div>";
		 
		 if ( isset($_SESSION["last_report"]) AND $_SESSION["last_report"] + $BanReportTime > time() ) {
		 $TimeLeft = time() - $_SESSION["last_report"];
		 $errors = "<div>".$lang["error_report_time"]." ".($BanReportTime-$TimeLeft)." ".$lang["error_sec"]." </div>";
		 }
		 
		 if ( empty($errors) ) {
		    $check = $db->query("SELECT * FROM gameplayers WHERE LOWER(name) = LOWER('".$player."') LIMIT 1");
			if ( $db->num_rows($check)<=0 ) {
			$errors.="<div>".$lang["error_no_player"]."</div>";
			
			$checkBan = $db->query("SELECT * FROM bans WHERE LOWER(name) = LOWER('".$player."') LIMIT 1");
			if ( $db->num_rows($check)>=1 ) {
			$errors.="<div>".$lang["error_already_banned"]."</div>";
			}
			
			} else {
			
			 $find = $db->query("SELECT * FROM stats WHERE LOWER(player) = '".$player."' LIMIT 1 ");
			 if ( $db->num_rows($find)>=1 ) {
			 $row = $db->fetch_array($find,'assoc');
			 $PID = $row["id"];
			 } 
			 else $PID = 0; //Player not ranked yet
			
			 $result = $db->query("INSERT INTO ban_reports(player_id, player_name, user_id, reason, game_url, replay_url, added, status, user_ip) VALUES('".$PID."', '".$player."', '".$_SESSION["user_id"]."', '".$reason."', '".$game_url."', '".$replay_url."', '".(int) time()."', '0', '".safeEscape($_SERVER["REMOTE_ADDR"])."')");
			 
			 $_SESSION["last_report"] = time();
			 header('location: '.$website.'?ban_report&success');
			 
			}

		 }
	  }
	  
   }
   
   //BAN APPEAL
   if ( isset($_GET["ban_appeal"])) {
      $BanAppeal = "";
	  
	  if (isset($_POST["submit_appeal"]) ) {
	     $player = safeEscape(trim($_POST["player_appeal"]));
		 $subject = safeEscape(trim($_POST["subject"]));
		 $reason = safeEscape(trim($_POST["message"]));
		 $reason = my_nl2br( trim($_POST["message"]) );
		 $reason = nl2br($reason);
		 $reason = EscapeStr( ($reason) );
		 $game_url   = EscapeStr(trim($_POST["game_url"]));
		 $replay_url = EscapeStr(trim($_POST["replay_url"]));
		 $errors = "";
		 
		 if (strlen($player)<=2 ) $errors.="<div>".$lang["error_report_player"]."</div>";
		 if (strlen($reason)<=3 ) $errors.="<div>".$lang["error_report_reason"]."</div>";
		  if ( !is_logged() )  $errors ="<div>".$lang["error_report_login"]."</div>";
		 
		 if ( isset($_SESSION["last_report"]) AND $_SESSION["last_report"] + $BanReportTime > time() ) {
		 $TimeLeft = time() - $_SESSION["last_report"];
		 $errors = "<div>".$lang["error_report_time2"]." ".($BanReportTime-$TimeLeft)." ".$lang["error_sec"]." </div>";
		 }
		 
		 if ( empty($errors) ) {
            $chk = $db->query("SELECT * FROM bans WHERE LOWER(name) = LOWER('".$player."') LIMIT 1");
			if ($db->num_rows($chk)<=0 ) $errors.="<div>".$lang["error_no_player"]."</div>";
			
			if ( empty($errors) ) {
			  $row = $db->fetch_array($chk,'assoc');
			  $PID = $row["id"];
			  $insert = $db->query("INSERT INTO ban_appeals(player_id, player_name, user_id, reason, game_url, replay_url, added, status, user_ip ) VALUES('".$PID."', '".$player."', '".$_SESSION["user_id"]."', '".$reason."', '".$game_url."', '".$replay_url."', '".(int) time()."', '0', '".safeEscape($_SERVER["REMOTE_ADDR"])."' )");
			  $_SESSION["last_report"] = time();
			  
			  header('location: '.$website.'?ban_appeal&success'); die;
			}
			
         }		 
	  }
	  
	  if ( !empty($_GET["ban_appeal"]) AND strlen($_GET["ban_appeal"])>=2  ) {
	  $BanAppeal = safeEscape( trim($_GET["ban_appeal"]));
	  $result  = $db->query("SELECT * FROM bans WHERE LOWER(name) = LOWER('".$BanAppeal."') ");
	      if ( $db->num_rows($result) >=1 ) {
	      $row = $db->fetch_array($result,'assoc');
		  $BanAppealName = $row["name"];
		  $BanAppealDate = $row["date"];
		  $BanAppealGamename= $row["gamename"];
		  $BanAppealAdmin= $row["admin"];
		  $BanAppealReason= $row["reason"];
		  $BanAppealServer= $row["server"];
	     }
	  }
   }
   
   //if ( isset($_GET["fb"]) ) include("inc/fb/connect.php");
?>